<template>
  <div class="admin-container">
    <h2>用户管理</h2>

    <!-- 操作按钮和搜索区域 -->
    <div class="action-bar">
      <div class="left">
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon> 新增用户
        </el-button>
      </div>
      <div class="right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名或手机号"
          class="search-input"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 用户列表 -->
    <el-table 
      :data="paginatedUserList" 
      border 
      v-loading="loading"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />
      <el-table-column prop="phoneNumber" label="手机号" width="150" />
      <el-table-column prop="role" label="角色" width="100">
        <template #default="scope">
          <el-tag :type="getRoleTagType(scope.row.role)">
            {{ mapRoleToText(scope.row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isDeleted" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isDeleted === 0 ? 'success' : 'danger'">
            {{ scope.row.isDeleted === 0 ? '正常' : '已删除' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="openEditDialog(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)" v-if="scope.row.isDeleted === 0">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="filteredUserList.length"
        :page-sizes="[5, 10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form 
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="passwordHash" v-if="dialogType === 'add'">
          <el-input 
            v-model="userForm.passwordHash" 
            type="password" 
            show-password 
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="userForm.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role" v-if="dialogType === 'add'">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="居民" value="resident" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { getAllUsers, updateUserByAdmin, deleteUserByAdmin, createAdmin } from '@/api/adminApi'

// 数据状态
const loading = ref(false)
const submitLoading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogType = ref('add')
const userFormRef = ref(null)
const userList = ref([])

// 用户表单数据
const userForm = ref({
  userId: null,
  username: '',
  passwordHash: '',
  email: '',
  phoneNumber: '',
  role: 'resident',
  isDeleted: 0
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  passwordHash: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^[0-9\s]+$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 计算属性：过滤用户列表
const filteredUserList = computed(() => {
  if (!searchKeyword.value) return userList.value
  const keyword = searchKeyword.value.toLowerCase()
  return userList.value.filter(user =>
    user.username.toLowerCase().includes(keyword) ||
    user.phoneNumber.includes(keyword)
  )
})

// 计算属性：分页用户列表
const paginatedUserList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUserList.value.slice(start, end)
})

// 角色标签类型
const getRoleTagType = (role) => {
  return role === 'admin' ? 'danger' : 'success'
}

// 角色文本映射
const mapRoleToText = (role) => {
  return role === 'admin' ? '管理员' : '居民'
}

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const response = await getAllUsers()
    if (response.code === 200) {
      userList.value = response.data.users
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 打开新增对话框
const openAddDialog = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  userForm.value = {
    userId: null,
    username: '',
    passwordHash: '',
    email: '',
    phoneNumber: '',
    role: 'resident',
    isDeleted: 0
  }
}

// 打开编辑对话框
const openEditDialog = (user) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  userForm.value = { ...user }
}

// 重置表单
const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          const response = await createAdmin(userForm.value)
          if (response.code === 200) {
            ElMessage.success('新增用户成功')
            fetchUserList()
            dialogVisible.value = false
          }
        } else {
          const response = await updateUserByAdmin(userForm.value)
          if (response.code === 200) {
            ElMessage.success('更新用户成功')
            fetchUserList()
            dialogVisible.value = false
          }
        }
      } catch (error) {
        ElMessage.error('操作失败')
        console.error(error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除用户
const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await deleteUserByAdmin(user.userId)
    if (response.code === 200) {
      ElMessage.success('删除用户成功')
      fetchUserList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 初始化
onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.admin-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-bottom: 20px;
}
</style>